class MyPage extends BasePopupEdit {
    constructor(dataId, pageStatus) {
        super(dataId, pageStatus);
        this._rows = 0;
    }
    OnPageLoad() {
        this.FetchForPage();
    }
    // 得到检索条件
    GetFilter() {
        let data = new Object();
        return $.toJSON(data);
    }
    //《按钮》显示全部
    FetchAll() {
        this.FetchForPage();
    }
    // 得到数据列表信息
    FetchForPage() {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/trade/production_instruction/lines/destination/fetch.html",
            timeout: 30 * 1000,
            data: JSON.stringify(parent.$("#HeaderId").val()),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done((data) => {
            this.BuildDataTable(data);
        }).fail((data) => {
            $("#loading").hide();
            ajaxError(data, 1);
        }).always(( ) => {
        });
    }
    BuildDataTable(result) {
        $("#tabData01 tbody").empty();

        if (result === null) {
            this._rows = 0;
            this.AutoAdjustTableHeightForLines();    // 自适应高度设置
            $('#loading').hide();
            return false;
        }
        this._rows = result.length;
        let content_01 = '';
        for (let i = 0; i < result.length; i++) {
            let sequence = i + 1;
            content_01 += '<tr _mash_linesid="' + result[i].linesId + '">';
            content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="_Instance.DoDelete($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td style="text-align:center;">' + sequence + '</td>';
            content_01 += '<td class="edited-cell">' + result[i].destination + '</td>';
            content_01 += '</tr>';

            $("#tabData01 tbody").append(content_01);
            content_01 = '';
        }

        setOneTableRowColor("tabData01");

        this.AutoAdjustTableHeightForLines();    // 自适应高度设置
        $("#loading").hide();

        let id = "cell_field";
        let name = "_cell_field";
        $('#tabData01 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        let _this = this;
        // 拖动表格行改变显示顺序
        $("#tabData01 tbody").wxdragsort({
            dragWrapper: $("#tabData01"),
            placeHolderWrapper: $("#divD1"),
            parentobj: $("#tabData01"),
            dragColumnIndex: 1,
            dragEnd: function () {
                _this.ResetRowNo();
            }
        });
    }
    // 拖动改变序号
    ResetRowNo() {
        // 设置拖动后的每行序号
        $("#tabData01 tbody").find("tr").each(function (index) {
            $(this).find("td").eq(1).text(index + 1);
        });

        let _result = [];
        $('#tabData01 tbody').find("tr").each(function () {
            let _linesId = $.trim($(this).attr("_mash_linesid"));
            let _orderNo = $.trim($(this).find('td').eq(1).text());   // 顺序号

            let item = {};
            item['headerId'] = parseInt(parent.$("#HeaderId").val());
            item['linesId'] = _linesId;
            item['orderNo'] = parseInt(_orderNo);
            item['updatedBy'] = parseInt(parent.$("#UserId").val());
            _result.push(item);
        });

        // 更新后台对应的序号
        super.DoAjax(_result, "/trade/production_instruction/lines/destination/order/update.html", function (data, $self) {
            if (data.Success) {
                $self.BuildDataTable(data.DestinationNode);
                // 设置目的地
                parent._InstancePageHeader.destinationNode = data.DestinationNode;
                // 显示明细数据
                parent._InstancePageLines.BuildDataTable(data.LinesList);

                ShowSuccessMessagePanel("顺序改变成功。");
                $(".success-msg").css({left: '240px', top: '6px'});
            }
        });
    }
    // 添加新行以及新行的操作方式
    InsertNewLines() {
        let $newLine = $('<tr class="newLine" _mash_linesid="">' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="_Instance.RemoveNewLine($(this))"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');
        $('#tabData01 tbody').prepend($newLine);   // 加在前面
        this._rows = this._rows + 1;

        setOneTableRowColor("tabData01");
        this.AutoAdjustTableHeightForLines();    // 自适应高度设置

        let id = "cell_field";
        let name = "_cell_field";
        $newLine.find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        return $newLine;
    }
    RemoveNewLine($self) {
        parent.showModal(333, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', () => {
            $self.parent().parent().remove();
            this._rows = this._rows - 1;
            this.AutoAdjustTableHeightForLines();    // 自适应高度设置
        });
    }
    // 得到交货目的地明细
    GetLinesData() {
        let jsonInsert = [];
        let jsonUpdate = [];
        let itemResult = {};
        let jsonResult = [];
        // 得到修改过数据
        $('#tabData01 tbody').find("tr").each(function () {
            let _linesId = $.trim($(this).attr('_mash_linesid'));          // LinesId
            let _orderNo = $.trim($(this).find('td').eq(1).text()) === '' ? null : $.trim($(this).find('td').eq(1).text());      // 顺序号
            let _destination = $.trim($(this).find('td').eq(2).text()) === '' ? null : $.trim($(this).find('td').eq(2).text());  // 目的地
            if ($(this).find("td.dirty").length) {
                let item = {};
                item['headerId'] = parseInt(parent.$("#HeaderId").val());
                item['linesId'] = _linesId;
                item['orderNo'] = _orderNo;
                item['destination'] = _destination;
                item['CreatedBy'] = parseInt(parent.$("#UserId").val());
                item['UpdatedBy'] = parseInt(parent.$("#UserId").val());

                if (_linesId === '') {
                    jsonInsert.push(item);
                } else {
                    jsonUpdate.push(item);
                }
            }
        });
        itemResult['insertList'] = jsonInsert;
        itemResult['updateList'] = jsonUpdate;
        jsonResult.push(itemResult);

        return itemResult;
    }
    // 保存
    DoSave() {
        //step 1、进行页面验证，失败则返回
        let success_01 = CheckGridInput();
        if (!success_01)
            return;

        //step 2、执行处理
        if (this.GetLinesData().insertList.length > 0 || this.GetLinesData().updateList.length > 0) {
            super.DoAjax(this.GetLinesData(), "/trade/production_instruction/lines/destination/save.html", function (data, $self) {
                if (data.Success) {
                    $self.BuildDataTable(data.DestinationNode);
                    // 设置目的地
                    parent._InstancePageHeader.destinationNode = data.DestinationNode;
                    // 显示明细数据
                    parent._InstancePageLines.BuildDataTable(data.LinesList);

                    ShowSuccessMessagePanel("增加成功。");
                    $(".success-msg").css({left: '240px', top: '6px'});
                }
            });
        }
    }
    DoDelete($self) {
        let _params = {};
        _params['HeaderId'] = parent.$("#HeaderId").val();
        _params['LinesId'] = $self.parent().parent().attr("_mash_linesid");
        _params['Destination'] = $self.parent().parent().find("td").eq(2).text();
        _params['DeletedBy'] = $("#UserId").val();

        parent.showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？', () => {
            super.DoAjax(_params, "/trade/production_instruction/lines/destination/delete.html", (data, $self) => {
                if (data.Success) {
                    $self.BuildDataTable(data.DestinationNode);
                    // 设置目的地
                    parent._InstancePageHeader.destinationNode = data.DestinationNode;
                    // 显示明细数据
                    parent._InstancePageLines.BuildDataTable(data.LinesList);
                    ShowSuccessMessagePanel("删除成功。");
                    $(".success-msg").css({left: '240px', top: '6px'});
                }
            });
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _top = $("#tabHeader01").offset().top + 25;
        let _rc = Math.floor((h - _top - 25) / 25);
        let _dh = _rc * 25;
        let _tah = this._rows * 25;
        _dh = (_tah >= _dh) ? _dh : _tah;

        $("#divD1").css({"max-height": _dh, height: _dh});
    }
}

let  _Instance = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    $("#form_data").data("changed", false);   // 初始化form数据提交状态
    _Instance = new MyPage(0, 1);
    _Instance.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
function CheckGridInput() {
    $('#tabData01 tbody').find("tr").each(function () {
        let $row = $(this);
        let _Destination = $.trim($(this).find('td').eq(2).text());   // 目的地

        if (_Destination === '') {
            GridCheckErrHandle($row, 2, '发货目的地不能为空。');
        } else {
            GridCheckSuccessHandle($row, 2);
        }
    });
    if ($('#tabData01 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        $(".error-msg").css({left: '240px', top: '6px'});
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}